/**
 * 
 */
package mblog.web.controller.front.comment;

import java.text.MessageFormat;

import mblog.core.pojos.Comment;
import mblog.web.controller.BaseController;
import mtons.modules.lang.Const;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Page;
import mtons.modules.pojos.UserProfile;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.pojos.enums.CommentType;
import com.faxsun.core.service.CommentService;
import com.faxsun.core.utils.PreviewHtmlUtils;

/**
 * @author langhsu
 * 
 *         为评论增加类型
 * @author songdragon
 *
 */
@Controller
@RequestMapping("/comment")
public class CommentController extends BaseController {
	@Autowired
	private CommentService commentService;

	@RequestMapping(value = "/list/{toId}", method = RequestMethod.GET,produces="application/json;charset=utf-8;")
	public @ResponseBody Page view(Integer pn, @PathVariable Long toId,
			Integer type) {
		Page page = wrapPage(pn);
		page.setCount(true);
		//FIXME:1 means comments has been published
		commentService.paging(page, toId, type,1);
		return page;
	}

	/**
	 * 返回评论显示的列表
	 * 
	 * @param pn
	 * @param toId
	 * @param type
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listPage/{toId}", method = RequestMethod.GET)
	public String viewHtml(Integer pn, @PathVariable Long toId, Integer type,
			ModelMap model) {
		Page page = wrapPage(pn);
		//FIXME:1 means comments has been published
		if(type == CommentType.INBOX.getIntValue()){
		    commentService.pagingInbox(page, toId, 1);		    
		}else{
	        commentService.paging(page, toId, type,1);		    
		}
		model.addAttribute("commentPage", page);
		return "/views/partials/commentList";
	}

	/**
	 * 提交评论
	 * 
	 * @param toId
	 * @param text
	 * @param type
	 * @return
	 */
	@RequestMapping("/post")
	public @ResponseBody Data post(Long toId, String text, Integer type) {
        //FIXME:对html转义字符，算作一个字符
        String summary=PreviewHtmlUtils.htmlRemoveTag(text);
		Data data = postData(toId, text, type, summary, true);
		return data;
	}

    @RequestMapping("/post/view")
    public String postView(Long toId, String text, Integer type, ModelMap model) {
        Data data = post(toId, text, type);
        return "redirect:/admin/comment/list?status=1&inboxAdd=" + data.getCode();
    }

    @RequestMapping(value= "/post/reply", method = RequestMethod.POST)
    public @ResponseBody Data postReply(String text, Integer type, Long toId, Long commentId, String commentToUserName, ModelMap model) {        
        String summary = PreviewHtmlUtils.htmlRemoveTag(text);
        
        int lengthLimit = 100;
        if(type == CommentType.LIVE.getIntValue() || type == CommentType.LIVEMSG.getIntValue()){
           lengthLimit = 200; 
        }
        
        if(summary.length() > lengthLimit){
           return Data.failure(-3, "评论长度不能超过" + lengthLimit + "字！");
        } 
        else if (StringUtils.isEmpty(text)){
        	return Data.failure(-3,"回复内容不能为空");
        }
        
        String replyPrefix = MessageFormat.format(CommentService.REPLY_FORMAT, commentId, commentToUserName);
        Data data = postData(toId, replyPrefix + text, type, null, false);
        return data;
    }
    
    private Data postData(Long toId, String text, Integer type, String summary, boolean checkLength){
        Data data = Data.failure("操作失败");
        UserProfile up = (UserProfile) session.getAttribute(Const.KEY_LOGIN);
        
        int lengthLimit = 100;
        if(type == CommentType.LIVE.getIntValue() || type == CommentType.LIVEMSG.getIntValue()){
           lengthLimit = 200; 
        }
        
        if(checkLength && summary.length() > lengthLimit){
            data=Data.failure(-3, "评论长度不能超过" + lengthLimit + "字！");
        } else if (up == null) {
            data = Data.failure(-2, "请先登陆!");
        } else {
            // FIXME: add validator for arguments
            if (toId > 0 && StringUtils.isNotEmpty(text) && type >= CommentType.PRODUCT.getIntValue()
                    && type <= CommentType.LIVEMSG.getIntValue()) {
                Comment c = new Comment();
                c.setToId(toId);                
                c.setContent(text);
                c.setType(type);
                commentService.post(c);
                data = Data.success("发表成功!", new CommentPostData(type, up.getId()));                
            }
        }
        return data;
    }
    
    public class CommentPostData{
        private int type;
        private long authorId;
        
        public CommentPostData(int type, long authorId) {
            super();
            this.type = type;
            this.authorId = authorId;
        }
        
        public int getType() {
            return type;
        }
        public void setType(int type) {
            this.type = type;
        }
        public long getAuthorId() {
            return authorId;
        }
        public void setAuthorId(long authorId) {
            this.authorId = authorId;
        }        
    }

}
